﻿using System;
using System.Linq;
using System.Threading;
using Coder.Workflow.ViewModel;
using Fee.FileAttachs;
using Fee.IO.Exporters;
using Fee.Orders;
using Fee.Orders.PreWorkflow;
using Fee.Orders.ViewModel;
using Fee.Searchers;
using Fee.Stores;
using Identity;
using JwtWebApi.Data;
using JwtWebApi.Filters;
using JwtWebApi.Models.ViewModel;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Cors;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;

namespace JwtWebApi.Controllers
{
    [Authorize]
    [Route("[controller]")]
    [ApiController]
    [EnableCors]
    public class PreDelegateOrderController : WorkflowBaseController<PreDelgateOrderManager<ApplicationDbContext>, PreDelegateOrder>
    {
        private readonly ApplicationDbContext _context;
        private readonly IPreDelegateOrderStore<ApplicationDbContext> _delegateOrderStore;
        private readonly FileManager _fileManager;
        private readonly PreDelgateOrderManager<ApplicationDbContext> _workflowManager;


        public PreDelegateOrderController(PreDelgateOrderManager<ApplicationDbContext> orderManager, ApplicationDbContext dbContext, ApplicationDbContext context, IPreDelegateOrderStore<ApplicationDbContext> delegateOrderStore, FileManager fileManager, PreDelgateOrderManager<ApplicationDbContext> workflowManager) : base(orderManager, dbContext)
        {
            _context = context;
            _delegateOrderStore = delegateOrderStore;
            _fileManager = fileManager;
            _workflowManager = workflowManager;
        }

        [HttpGet("list")]
        public IActionResult List([FromQuery] DelegateOrderSearch searcher)
        {
            var query = _delegateOrderStore.List(searcher, out var total);
            return Json(new
            {
                total,
                data = query
            });
        }

        [HttpPost("create")]
        public IActionResult CreateDelegateOrder([FromBody] CreatePreDeleageOrderViewModel model)
        {
            var result = _workflowManager.CreateOrder(model.StationId,
                User.Identity.Name, DateTimeOffset.Now, null);

            var order = result.Successed ? new OrderViewModel(result.Order) : null;
            return Json(new
            {
                successed = result.Successed,
                message = result.Message,
                order
            });
        }

        [HttpPost("confirm-create-order")]
        public IActionResult CreateOrderConfirm([FromBody] CreatePreDeleageOrderViewModel model)
        {
            var result = _workflowManager.CreateOrder(model.StationId,
                User.Identity.Name, DateTimeOffset.Now, null);

            result = _workflowManager.OrderConfirm(result.Order,
                model.Details.Select(f => f.ToDelegateOrderDetail(_context)));


            return Json(new
            {
                successed = result.Successed,
                message = result.Message,
                order = result.Successed ? new OrderViewModel(result.Order) : null
            });
        }

        [HttpPost("submit-to-workflow")]
        public IActionResult SubmitToWorkflow([FromBody] CreatePreDeleageOrderViewModel model)
        {
            var result = _workflowManager.CreateOrder(model.StationId,
                User.Identity.Name, DateTimeOffset.Now, null);
            if (!result.Successed) return Json(result);
            result = _workflowManager.OrderConfirm(result.Order,
                model.Details.Select(f => f.ToDelegateOrderDetail(_context)));
            _workflowManager.Start(result.Order);
            return Json(new
            {
                successed = result.Successed,
                message = result.Message,
                order = result.Successed ? new OrderViewModel(result.Order) : null
            });
        }


        [HttpGet("work-activity/{id:int}")]
        public override IActionResult GetByWorkActionResult(int id)
        {
            var workflowInstanceItem = _workflowManager.GetWorkActivity(id, true);

            var r = new WorkActivityViewData<OrderViewModel>(workflowInstanceItem);
            r.ProcessInstance = new OrderViewModel((DelegateOrderBase)workflowInstanceItem.ProcessInstance);
            return Json(r);
        }


        


        [HttpPost("save/details/{id:int}")]
        public IActionResult SaveDetail([FromBody] DelegateOrderData data, [FromRoute] int id)
        {
            var user = _context.GetByUserName(User.Identity.Name);
            var result = _workflowManager.UpdateWorkContent(data.Details.Select(f => f.ToDelegateOrderDetail(_context)),
                id, user);
            return Ok(result);
        }

        //[HttpGet("get/{id:int}")]
        //public override IActionResult Get([FromRoute] int id)
        //{
        //    var result = _delegateOrderStore.GetById(id);
        //    return Json(new OrderViewModel(result));
        //}

        [HttpGet("myTask")]
        public IActionResult GetMyTask([FromQuery] DelegateWorkActivitySearch searcher)
        {
            var task
                = _workflowManager.GetMyTask(searcher, out var total);

            return Json(new
            {
                data = task,
                total
            });
        }

        //[HttpGet("task/export")]
        //public IActionResult ExportExcel([FromQuery] DelegateWorkActivitySearch searcher)
        //{
        //    searcher.PageSize = 100 * 1000;
        //    var task
        //        = _workflowManager.GetMyTask(searcher, out var total);

        //    var fileName = _fileManager.GetTempPrivateFile(".xlsx", User.Identity);


        //    var stream = System.IO.File.OpenWrite(fileName);

        //    var
        //        exporter = new StationWorkActivityExporter();
        //    exporter.ToExcel(stream, task);


        //    return File(System.IO.File.OpenRead(fileName), "APPLICATION/octet-stream");

        //}
    }
}